package leetcode.code1208;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int equalSubstring(String s, String t, int maxCost) {
		int[] diffs = new int[s.length()];
		for (int i = 0; i < diffs.length; i++) {
			diffs[i] = Math.abs(s.charAt(i) - t.charAt(i));
		}
		int ans = 0, l = 0, r = s.length();
		while (l <= r) {
			int mid = ((r - l) >> 1) + l;
			int minCost = this.f(diffs, mid);
			if (minCost <= maxCost) {
				ans = mid;
				l = mid + 1;
			} else {
				r = mid - 1;
			}
		}
		return ans;
	}

	private int f(int[] diffs, int mid) {
		int r = 0;
		int sum = 0;
		while (r < mid) {
			sum += diffs[r++];
		}
		int ans = sum;
		while (r < diffs.length) {
			sum += -diffs[r - mid] + diffs[r];
			ans = Math.min(sum, ans);
			r++;
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(19, this.equalSubstring("tyiraojpcfuttwblehv", "stbtakjkampohttraky", 119));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
